<template>
  <div class="publish-product-container">
    <div class="page-header">
      <h2>发布商品</h2>
      <p>请填写商品信息，所有带 * 的为必填项</p>
    </div>

    <el-card>
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="120px"
        class="product-form"
      >
        <el-form-item label="商品标题" prop="title">
          <el-input
            v-model="productForm.title"
            placeholder="请输入商品标题"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="商品分类" prop="categoryId">
          <el-select
            v-model="productForm.categoryId"
            placeholder="请选择商品分类"
          >
            <el-option
              v-for="category in mockCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="productForm.price"
            placeholder="请输入商品价格"
            :min="0"
            :step="0.01"
            style="width: 100%"
          >
            <template #prepend>¥</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="商品图片" prop="images">
          <el-upload
            v-model:file-list="fileList"
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="handleImageChange"
            :on-remove="handleImageRemove"
            :limit="5"
            :on-exceed="handleExceed"
          >
            <el-icon><i-ep-plus /></el-icon>
            <template #file="{ file }">
              <div>
                <img :src="file.url" class="el-upload-list__item-thumbnail" />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <el-icon><i-ep-zoom-in /></el-icon>
                  </span>
                  <span
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <el-icon><i-ep-delete /></el-icon>
                  </span>
                </span>
              </div>
            </template>
          </el-upload>
          <el-dialog v-model="dialogVisible" :title="'预览'" width="800px">
            <img width="100%" :src="dialogImageUrl" alt="预览" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            placeholder="请详细描述商品的新旧程度、使用情况、转让原因等信息"
            rows="8"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="商品参数">
          <el-button type="primary" @click="addParam" size="small">
            <el-icon><i-ep-plus /></el-icon>
            添加参数
          </el-button>
          <div v-for="(param, index) in productForm.params" :key="index" class="param-item">
            <el-input
              v-model="param.name"
              placeholder="参数名"
              style="width: 200px; margin-right: 10px"
            />
            <el-input
              v-model="param.value"
              placeholder="参数值"
              style="flex: 1; margin-right: 10px"
            />
            <el-button type="danger" @click="removeParam(index)" size="small">
              <el-icon><i-ep-delete /></el-icon>
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="交易方式" prop="tradeMethod">
          <el-checkbox-group v-model="productForm.tradeMethod">
            <el-checkbox label="face_to_face">面对面交易</el-checkbox>
            <el-checkbox label="express">快递配送</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="交易地点" prop="tradeLocation">
          <el-input
            v-model="productForm.tradeLocation"
            placeholder="请输入交易地点（如：XX教学楼）"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">发布商品</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useProductStore } from '../../store'

const router = useRouter()
const productStore = useProductStore()
const productFormRef = ref(null)

const productForm = reactive({
  title: '',
  categoryId: '',
  price: null,
  images: [],
  description: '',
  params: [],
  tradeMethod: [],
  tradeLocation: ''
})

const fileList = ref([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

// 模拟分类数据
const mockCategories = [
  { id: 1, name: '数码产品' },
  { id: 2, name: '图书文具' },
  { id: 3, name: '服装鞋包' },
  { id: 4, name: '生活用品' },
  { id: 5, name: '运动器材' },
  { id: 6, name: '其他' }
]

const productRules = {
  title: [
    { required: true, message: '请输入商品标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度在 5 到 50 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' }
  ],
  images: [
    { required: true, message: '请至少上传一张商品图片', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 10, max: 2000, message: '描述长度在 10 到 2000 个字符', trigger: 'blur' }
  ],
  tradeMethod: [
    { required: true, message: '请选择交易方式', trigger: 'change' }
  ],
  tradeLocation: [
    { required: true, message: '请输入交易地点', trigger: 'blur' }
  ]
}

const addParam = () => {
  productForm.params.push({ name: '', value: '' })
}

const removeParam = (index) => {
  productForm.params.splice(index, 1)
}

const handleImageChange = (uploadFile, uploadFiles) => {
  // 将文件转换为base64用于预览
  const reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw)
  reader.onload = (e) => {
    uploadFile.url = e.target.result
    productForm.images = uploadFiles.map(file => file.url)
  }
}

const handleImageRemove = (uploadFile, uploadFiles) => {
  productForm.images = uploadFiles.map(file => file.url)
}

const handleExceed = (files, fileList) => {
  ElMessage.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

const handleRemove = (file) => {
  const index = fileList.value.indexOf(file)
  if (index > -1) {
    fileList.value.splice(index, 1)
    productForm.images = fileList.value.map(f => f.url)
  }
}

const handleSubmit = async () => {
  await productFormRef.value.validate()
  try {
    // 在实际应用中，这里应该调用API上传图片并创建商品
    // await productStore.createProduct(productForm)
    
    ElMessage.success('商品发布成功')
    router.push('/products')
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '发布失败，请稍后重试')
  }
}

const handleCancel = () => {
  router.push('/products')
}
</script>

<style scoped>
.publish-product-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.page-header p {
  color: #666;
}

.product-form {
  width: 100%;
  max-width: 800px;
}

.param-item {
  display: flex;
  align-items: center;
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.el-upload-list__item {
  width: 180px;
  height: 180px;
}

.el-upload-list__item-thumbnail {
  width: 180px;
  height: 180px;
}

.el-upload--picture-card {
  width: 180px;
  height: 180px;
  line-height: 180px;
}

@media (max-width: 768px) {
  .param-item {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .param-item .el-input {
    width: 100% !important;
    margin-right: 0 !important;
  }
  
  .el-upload-list__item,
  .el-upload--picture-card {
    width: 120px;
    height: 120px;
  }
  
  .el-upload-list__item-thumbnail {
    width: 120px;
    height: 120px;
  }
}
</style>